package com.terios.logic;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

import com.terios.AuthorizeUser;
import com.terios.conts.CommonStrs;
import com.terios.logic.ui.LoginActivity;
import com.terios.util.SaveLoginParam;
import com.weibo.net.AccessToken;
import com.weibo.net.DialogError;
import com.weibo.net.Utility;
import com.weibo.net.Weibo;
import com.weibo.net.WeiboDialogListener;
import com.weibo.net.WeiboException;

/**
 * OAuth2Activity.java 2012-9-29 下午12:04:25
 * 
 * @author Wang Tengrui
 */
public class OAuth2Activity extends Activity {
	public static Weibo mWeibo = null;
	public AuthorizeUser nowUser;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(getWindow().FEATURE_NO_TITLE);// 取消标题显示
		mWeibo = Weibo.getInstance();
		mWeibo.setupConsumerConfig(CommonStrs.CONSUMER_KEY,
				CommonStrs.CONSUMER_SECRET);
		mWeibo.setRedirectUrl(CommonStrs.mRedirectUrl);
		mWeibo.authorize(OAuth2Activity.this, new AuthDialogListener());
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		Utility.clearCookies(this);
		super.onDestroy();
	}

	class AuthDialogListener implements WeiboDialogListener {

		/**
		 * 授权完成之后保存授权用户信息
		 */
		@Override
		public void onComplete(Bundle values) {
			String token = values.getString("access_token");
			String expires_in = values.getString("expires_in");

			String expires_date = String.valueOf(System.currentTimeMillis()
					+ Long.parseLong(expires_in) * 1000);// 把expires_in换算成过期时间存入expires_date
			values.putString("expires_date", expires_date);// 添加过期时间

			AccessToken accessToken = new AccessToken(token,
					CommonStrs.CONSUMER_SECRET);

			accessToken.setExpiresIn(expires_in);
			Weibo.getInstance().setAccessToken(accessToken);
			SaveLoginParam.saveNowUser(OAuth2Activity.this, values);// 把当前用户保存到SharedPreferences
			SaveLoginParam.saveAuthorizeUser(OAuth2Activity.this, values);// 把授权用户户保存到数据库中

			startActivity(new Intent(OAuth2Activity.this, LoginActivity.class));
		}

		@Override
		public void onWeiboException(WeiboException e) {
			Toast.makeText(getApplicationContext(), "授权异常 : " + e.getMessage(),
					Toast.LENGTH_LONG).show();
		}

		@Override
		public void onError(DialogError e) {
			Toast.makeText(getApplicationContext(), "授权失败 : " + e.getMessage(),
					Toast.LENGTH_LONG).show();
		}

		@Override
		public void onCancel() {
			Toast.makeText(getApplicationContext(), "取消授权", Toast.LENGTH_LONG)
					.show();
		}

	}
}
